package com.tea.modules;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.ssl.SSLContextBuilder;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * com.tea.modules
 *
 * @author jaymin
 * @since 2021/7/29
 */
public class ClientTwoWaySSL {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        FileInputStream keyStoreIn = new FileInputStream("D:\\Java\\Demo\\redis\\spring-web\\src\\main\\resources\\clientKeystore.jks");
        FileInputStream trustStoreIn = new FileInputStream("D:\\Java\\Demo\\redis\\spring-web\\src\\main\\resources\\clientTruststore.jks");

        try {
            keyStore.load(keyStoreIn, "123ABCdef*".toCharArray());
            trustStore.load(trustStoreIn, "123ABCdef*".toCharArray());
        } finally {
            keyStoreIn.close();
            trustStoreIn.close();
        }

        SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore, "123ABCdef*", trustStore);
        Scheme sch = new Scheme("https", socketFactory, 8080);

        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpGet httpget = new HttpGet("https://127.0.0.1:8080/hello");
        System.out.println("Request:" + httpget.getRequestLine());

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: "
                    + entity.getContentLength());
        }
        if (entity != null) {
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    }
}
